'use strict'

const mysql = require('mysql');
const Fiber = require('fibers');
const config = require('../config').mysql;

// 使用连接池提升性能
// https://en.wikipedia.org/wiki/Connection_pool
const pool = mysql.createPool({
    connectionLimit: 10,
    host: config.host,
    port: config.port,
    user: config.user,
    password: config.password,
    database: config.database,
    supportBigNumbers: true,
    multipleStatements: true
});

pool.on('connection', function (connection) {
    console.log('database connected!');
});

exports.pool = pool;

exports.query = function (sql) {
    let fiber = Fiber.current;
    let ret = {
        err: null,
        rows: null,
        fields: null,
    };
    pool.getConnection(function (err, connection) {
        connection.query(sql, function (error, results, fields) {
            connection.release();
            ret.err = error;
            if (error) {
                console.log('error running query', error);
            } else {
                ret.rows = results;
                ret.fields = fiedls;
            }
            fiber.run();
        });
    });
    Fiber.yield();
    return ret;
};

// 调用代理录存储过程
exports.agentLogin = function (unionid, name, callback) {
    let resp = {
        ret: 0,
        userid: 0,
        nickname: name,
        tx_cash: 0,
        today_cash: 0,
        superior_id: 0,
    };
    let sql = "SET @unionid='" + unionid + "';SET @name='" + name + "';SET @ret=0;";
    sql += "CALL mjjy_agent.cp_agent_auth(@unionid,@name,@ret);SELECT @ret AS ret;";
    console.log("zh:"+sql);
    pool.getConnection(function (err, connection) {
        let db_ret = 0;
        if (err) {
            console.log(err);
            if (callback) {
                callback(resp);
            }
            return;
        }
        connection.query(sql, (error, results, fields) => {
            connection.release();
            if (error) {
                resp.ret = -1;
                console.log('error running query', error);
            } else {
                // 获取返回值
                for (let i = fields.length - 1; i >= 0; i--) {
                    if (fields[i] && fields[i][0].name == 'ret') {
                        resp.ret = results[i][0].ret;
                        break;
                    }
                }
            }
            if (resp.ret == 1) {
                // 获取结果
                for (let i = fields.length - 1; i >= 0; i--) {
                    if (fields[i] && fields[i][0].name == 'userid') {
                        resp.userid = results[i][0].userid;
                        resp.tx_cash = results[i][0].tx_cash;
                        resp.today_cash = results[i][0].today_cash;
                        resp.superior_id = results[i][0].superior_id;
                        break;
                    }
                }
            }
            if (callback) {
                callback(resp);
            }
        });
    });
};

// 调用代理账号登录存储过程
exports.agentLoginZH = function (userid, password, callback) {
    let resp = {
        ret: 0,
        userid: userid,
        nickname: '',
        tx_cash: 0,
        today_cash: 0,
        superior_id: 0,
    };
    let sql = "SET @userid='" + userid + "';SET @password='" + password + "';SET @ret=0;";
    sql += "CALL mjjy_agent.cp_agent_zh(@userid,@password,@ret);SELECT @ret AS ret;";
    console.log("zh:"+sql);
    pool.getConnection(function (err, connection) {
        let db_ret = 0;
        if (err) {
            console.log(err);
            if (callback) {
                callback(resp);
            }
            return;
        }
        connection.query(sql, (error, results, fields) => {
            connection.release();
            if (error) {
                resp.ret = -1;
                console.log('error running query', error);
            } else {
                // 获取返回值
                for (let i = fields.length - 1; i >= 0; i--) {
                    if (fields[i] && fields[i][0].name == 'ret') {
                        resp.ret = results[i][0].ret;
                        break;
                    }
                }
            }
            if (resp.ret == 1) {
                // 获取结果
                for (let i = fields.length - 1; i >= 0; i--) {
                    if (fields[i] && fields[i][0].name == 'userid') {
                        resp.tx_cash = results[i][0].tx_cash;
                        resp.today_cash = results[i][0].today_cash;
                        resp.superior_id = results[i][0].superior_id;
                        break;
                    }
                }
            }
            if (callback) {
                callback(resp);
            }
        });
    });
};

// 查询下级
exports.agentSub = function (userid, type, callback) {
    let resp = {
        ret: 0,
        userid: userid,
        list: [],
    };
    let sql = "SET @userid='" + userid + "';SET @type='" + type + "';SET @ret=0;";
    sql += "CALL mjjy_agent.cp_agent_sub(@userid,@type,@ret);SELECT @ret AS ret;";
    pool.getConnection(function (err, connection) {
        let db_ret = 0;
        if (err) {
            console.log(err);
            if (callback) {
                callback(resp);
            }
            return;
        }
        connection.query(sql, (error, results, fields) => {
            connection.release();
            if (error) {
                resp.ret = -1;
                console.log('error running query', error);
            } else {
                // 获取返回值
                for (let i = fields.length - 1; i >= 0; i--) {
                    if (fields[i] && fields[i][0].name == 'ret') {
                        resp.ret = results[i][0].ret;
                        break;
                    }
                }
            }
            if (resp.ret == 1) {
                // 获取结果
                for (let i = fields.length - 1; i >= 0; i--) {
                    if (fields[i] && fields[i][0].name == 'userid') {
                        resp.list = results[i];
                        break;
                    }
                }
            }
            if (callback) {
                callback(resp);
            }
        });
    });
};

// 查询提现订单
exports.agentOrder = function (userid, callback) {
    let resp = {
        ret: 0,
        userid: userid,
        list: [],
    };
    let sql = "SET @userid='" + userid + "';";
    sql += "CALL mjjy_agent.cp_cash_order(@userid);";
    console.log(sql);
    pool.getConnection(function (err, connection) {
        let db_ret = 0;
        if (err) {
            console.log(err);
            if (callback) {
                callback(resp);
            }
            return;
        }
        connection.query(sql, (error, results, fields) => {
            connection.release();
            if (error) {
                resp.ret = -1;
                console.log('error running query', error);
            } else {
                // 获取结果
                for (let i = fields.length - 1; i >= 0; i--) {
                    if (fields[i] && fields[i][0].name == 'Dates') {
                        resp.list = results[i];
                        break;
                    }
                }
                if (callback) {
                    callback(resp);
                }
            }
        });
    });
};

// 查询收益明细
exports.profitDetail = function (userid, date, leixin, callback) {
    let resp = {
        ret: 0,
        userid: userid,
        list: [],
    };
    let sql = "SET @userid='" + userid + "';SET @date='" + date + "';SET @leixin="+ leixin +";";
    sql += "CALL mjjy_agent.cp_profit_detail(@userid,@date,@leixin);";
    pool.getConnection(function (err, connection) {
        let db_ret = 0;
        if (err) {
            console.log(err);
            if (callback) {
                callback(resp);
            }
            return;
        }
        connection.query(sql, (error, results, fields) => {
            connection.release();
            if (error) {
                resp.ret = -1;
                console.log('error running query', error);
            } else {
                // 获取结果 leixin=0是玩家收益，否则是代理收益
                if(leixin == 0){
                    for (let i = fields.length - 1; i >= 0; i--) {
                        if (fields[i] && fields[i][0].name == 'playerid') {
                            resp.list = results[i];
                            break;
                        }
                    }
                } else {
                    for (let i = fields.length - 1; i >= 0; i--) {
                        if (fields[i] && fields[i][0].name == 'subid') {
                            resp.list = results[i];
                            break;
                        }
                    }
                }
                if (callback) {
                    callback(resp);
                }
            }
        });
    });
};

// 提现
exports.doTx_cash = function (userid, tx_cash, callback) {
    let resp = {
        ret: 0,
    };
    let sql = "SET @userid='" + userid + "';SET @txCash='" + tx_cash + "';";
    sql += "CALL mjjy_agent.cp_tx(@userid,@txCash,@ret);SELECT @ret AS ret;";
    console.log("[db]doTx_cash sql="+sql);
    pool.getConnection(function (err, connection) {
        if (err) {
            console.log(err);
            if (callback) {
                callback(resp);
            }
            return;
        }
        connection.query(sql, (error, results, fields) => {
            connection.release();
            if (error) {
                resp.ret = -1;
                console.log('[db]doTx_Cash error running query', error);
            } else {
                // 获取返回值
                for (let i = fields.length - 1; i >= 0; i--) {
                    if (fields[i] && fields[i][0].name == 'ret') {
                        resp.ret = results[i][0].ret;
                        break;
                    }
                }
            }
            console.log("[db]doTx_cash return ret="+resp.ret);
            if (callback) {
                callback(resp);
            }
            
        });
    });
};

